# -*- coding:utf-8 -*-
#------功能：实现单个会话登录并发帖
import time
from urllib.parse import urlencode

import requests
from requests.cookies import RequestsCookieJar
from requests.adapters import HTTPAdapter

# /e/member/login/
# 测试是否开通空间
# /e/member/mspace/index.php
def writetxt(msg):
    try:
        with open('links1.txt', 'a+', encoding='utf-8') as f:
            f.write(msg + '\n')
    except:
        pass

def run(host,username,password,email,title,content,userinfo):
    print('开始时间')
    print(time.strftime('%Y-%m-%d %H:%M:%S'))
    # header 伪装浏览器设置
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Accept-Encoding': 'gzip',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Host': host,
        'X-Real-IP': '225.58.45.24',
        'X-Forwarded-For': '8.8.8.8',
        'Connection': 'keep-alive'
    }

    # -----------用Get 获取 网站信息
    # 为请求建立一个会话，保持状态，以后的url都用这个session来get post
    # session 是一个会话，他可以获得现在的cookie headers
    session = requests.Session()
    # session.adapters.DEFAULT_RETRIES = 5  # 增加重连次数
    # 给会话添加headers ，不用每次都带上headers了
    session.headers = headers



    # 会话请求 一个url，方式get ，https解除访问屏蔽verify=False
    # html 是会话请求的结果，它可以获得当前的网页内容html.text

    # 1-----------注册成功
    # 设置post提交格式

    #注册函数
    def get1():
        postData = {
            'enews': 'register',
            'groupid': '1',
            'tobind': '0',
            'username': username,
            'password': password,
            'repassword': password,
            'email': email,
            'truename': '',
            'oicq': '',
            'msn': '',
            'mycall': '',
            'phone': '',
            'homepage': '',
            'userpicfile': '(binary)',
            'address': '',
            'zip': '',
            'saytext': userinfo,
            'Submit': '(unable to decode value)'
        }
        # data_gb2312 = urlencode(postData, encoding='gb2312')
        # data_utf = urlencode(postData, encoding='utf-8')
        html1 = session.post(url=f'http://{host}/e/member/doaction.php', data=postData, verify=False, timeout=125)
        # print(session.cookies.get_dict())
        encode = html1.apparent_encoding
        print(html1.text)

    #发帖发帖函数
    def get2():
        # 2----------Post发帖,公告模块
        datas = {
            'spacename': title,
            'spacegg': content,
            'Submit': '(unable to decode value)',
            'enews': 'DoSetSpace'
        }
        url = f'http://{host}/e/member/mspace/index.php'
        # 将form提交数据转换成网页对应合适，本网站的格式gb2312，然后不要用datas直接放到会话请求里边，用转换好的格式data_gb2312来请求
        data_gb2312 = urlencode(datas, encoding='utf-8')
        html2 = session.post(url=url, data=data_gb2312, verify=False, timeout=125)
        print(html2.text.encode('ISO-8859-1').decode('utf-8'))
        # print(session.cookies.get_dict())

        # 用户的id号码是
        class user():
            id = ''
            username = ''
        user.id = session.cookies.get_dict()['iwuhbmluserid']
        user.username = session.cookies.get_dict()['iwuhbmlusername']
        # print(user)
        writetxt(f'http://{host}/e/space/?userid={user.id}')
        session.close()

    #登录函数
    def get3():
        postData = {
            'ecmsfrom': '',
            'enews': 'login',
            'tobind': '0',
            'username': username,
            'password': password,
            'lifetime': '99990',
            'Submit': '(unable to decode value)'}
        data_utf = urlencode(postData, encoding='utf-8')
        html3 = session.post(url=f'http://{host}/e/member/doaction.php', data=data_utf, verify=False,timeout=125)
        print(session.cookies.get_dict())

    try:
        get1()
    except requests.exceptions.RequestException as e:
        print('注册超时抛出例外，重新运行get1')
        print(e)
        get1()
        print(time.strftime('%Y-%m-%d %H:%M:%S'))
    except Exception as e:
        print("注册错误了，错误代码是")
        print(e)

    try:
        get2()
    except requests.exceptions.RequestException as e:
        print('提交函数超时抛出例外，重新运行get2')
        print(e)
        get2()
        print(time.strftime('%Y-%m-%d %H:%M:%S'))
    except Exception as e:
        print("已经注册错误了，用get3登录")
        print(e)
        try:
            get3()
        except requests.exceptions.RequestException as e:
            print('注册超时抛出例外，重新运行get3')
            get3()
        except Exception as e:
            print("登录错误了，错误代码是")
            print(e)


# if __name__ == '__main__':

    # run('www.farpop.com', 'shenhuawade', 'xiaogege123', 'email', '我们一起出发啊', '你要不哟啊一起', '这个是我的个人信息')
